<?php

use Illuminate\Database\Eloquent\ModelNotFoundException;

class AdminUserController extends AdminController {

	public function getIndex(){
		if(!Cache::has('user-all-data')){
			$data = User::all();
			Cache::put('user-all-data', $data, 30);
		}

		$data = Cache::get('user-all-data');

		$this->layout->title = trans('user.listuser');
		$this->layout->content = View::make('admin.user.index', array('data' => $data));
	}

	public function getCreate(){
		if(!Cache::has('user-list-group')){
			$data = DB::table('user_group')->whereNull('deleted_at')->lists('group', 'id');
			Cache::put('user-list-group', $data, 30);
		}

		$group = Cache::get('user-list-group');
		
		$this->layout->title = trans('user.create');
		$this->layout->content = View::make('admin.user.form', array('group' => $group));
	}

	public function getEdit($id){
		$this->layout->title = trans('user.edit');

		try{
			$model = new User;
			$data = $model->findOrFail($id);

			if(!Cache::has('user-list-group')){
				$data = DB::table('user_group')->whereNull('deleted_at')->lists('group', 'id');
				Cache::put('user-list-group', $data, 30);
			}

			$group = Cache::get('user-list-group');

			$this->layout->content = View::make('admin.user.form', array('user' => $data, 'group' => $group));
		}catch(ModelNotFoundException $e){
			App::abort(404);
		}
	}

	public function postSave(){
		$this->layout = null;

		$data = Input::all();

		$model = new User;

		$validator = $model->validator($data);

		if($validator->fails()){
			if(isset($data['id']) && $data['id'] > 0){
				$url = 'admin/user/edit/' . $data['id'];
			}else{
				$url = 'admin/user/create/';
			}

			return Redirect::to($url)->with('errors', $model->getErrorMessages());
		}else{
			$model->saveData($data);
			return Redirect::to('admin/user/');
		}
	}

	public function getDelete($id){
		$this->layout = null;

		try{
			$model = new User;
			$data = $model->findOrFail($id);
			$data->delete();
			Cache::pull('user-all-data');
			
			return Redirect::to('admin/user/')->with('message', trans('user.deleted'));
		}catch(ModelNotFoundException $e){
			App::abort(404);
		}
	}
}
